import cn from 'classnames';
import PropTypes from 'prop-types';
import React, { useState } from 'react';
import { withRouter } from 'react-router';
import { searchStringBuilder } from '@kuiper-components/page-table';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
import EmptyData from '../../../components/empty/EmptyData';

import Detail from './Detail';
import { datetime } from '../../../../common/formatter';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import s from './style.module.css';
import Toolbox from './Toolbox';
import fetch from 'API/fetch';

const routePrefix = '/policy-manage/general/operation-log';

const columns = [
	{
		title: '操作者',
		key: 'username',
		dataIndex: 'username',
	},
	{
		title: '操作行为',
		key: 'message',
		dataIndex: 'actionMessage',
		render(actionMessage) {
			return actionMessage || '- -';
		},
	},
	{
		title: '资产地址',
		key: 'affects',
		dataIndex: 'affects',
		render(affects) {
			return (
				<div className={s.affects} title={affects.join(' ')}>
					{affects?.length > 0 ? (affects.join(' ') || '- -') : '- -'}
				</div>
			);
		},
	},
	{
		title: '操作时间',
		key: 'createTime',
		dataIndex: 'createTime',
		render: datetime,
	},
	{
		title: '操作者IP',
		key: 'ip',
		dataIndex: 'ip',
		render(e) {
			return <span>{e || '- -'}</span>;
		},
	},
	{
		title: '详情',
		key: 'detail',
		dataIndex: 'detail',
		render(detail) {
			return <Detail detail={detail} />;
		},
	},
];
function OperationLog({ className, history, location, pagination = {} }) {
	const filter = JSON.parse(
		new URLSearchParams(location.search).get('filter') || '{}'
	);
	const [tableData, setData] = useState([]);
	const [count, setCount] = useState(0);
	const [page, setPage] = useState(1);
	const [perPage, setPerpage] = useState(10);
	const [loading, setLoading] = useState(false);
	const [type, setType] = useState('empty');
	const [otherQuery, setQuery] = useState(filter);

	const turnToUrlparam = obj => {
		let urls = '';
		const hasValKey = Object.keys(obj)
			.filter(
				item =>
					obj[item] ||
					obj[item] === false ||
					(typeof obj[item] !== 'string' && obj[item] == 0)
			)
			.map(i => {
				return i + '=' + obj[i];
			});
		urls = hasValKey.join('&');
		return urls;
	};
	const getData = (num, size) => {
		setLoading(true);
		const querydata = {
			page: num || 1,
			count: size || 10,
			affects: otherQuery.affects || '',
			startTime: otherQuery.startTime
				? new Date(otherQuery.startTime).toISOString()
				: '',
			endTime: otherQuery.endTime
				? new Date(otherQuery.endTime).toISOString()
				: '',
		};
		const params = turnToUrlparam(querydata);
		fetch(`/api/v2/audit/audit-result?${params}`, {
			method: 'GET',
		})
			.then(res => {
				const { results, count } = res.data;
				setCount(count);
				setData(results);
			})
			.finally(() => {
				setType('img');
				setLoading(false);
			});
	};

	const handleFilterChange = val => {
		if ((val.startTime && val.endTime) || (!val.startTime && !val.endTime)) {
			setQuery(val);
		}
		setPage(1);
		setPerpage(10);
		const search = searchStringBuilder(location.search, {
			filter: JSON.stringify(val),
			page: 1,
			sort: '_ID_DESC',
		});
		history.replace(`${routePrefix}?${search}`);
	};

	React.useMemo(() => getData(1, perPage), [otherQuery, perPage]);
	return (
		<div className={cn(className, s.operationLog)}>
			<Breadcrumb>
				<Item disabled key="policy-manage">
					综合管理
				</Item>
				<Item key="operation-log">操作日志</Item>
			</Breadcrumb>
			<div className={s.content}>
				<Toolbox onChange={handleFilterChange} value={filter} />
				<div className={s.tableContainer}>
					<Table
						columns={columns}
						data={tableData}
						pro
						loading={loading}
						empty={<EmptyData type={type} className={s.nobor} />}
					/>
					{count > 10 && (
						<div className={s.df}>
							<Pagination
								pageSize={perPage}
								current={Number(page || 1)}
								pageSizeOptions={[10, 20, 50]}
								showSizeChanger
								showQuickJumper
								showTotal={total => `共${total}条`}
								total={count}
								onChange={(page, pageSize) => {
									setPerpage(pageSize || 10);
									setPage(page || 1);
									getData(page, pageSize);
								}}
							/>
						</div>
					)}
				</div>
			</div>
		</div>
	);
}

OperationLog.propTypes = {
	className: PropTypes.string,
	history: PropTypes.objectOf(
		PropTypes.shape({
			push: PropTypes.func.isRequired,
		})
	),
	location: PropTypes.objectOf(
		PropTypes.shape({
			search: PropTypes.object,
		})
	),
};
OperationLog.defaultProps = {
	className: '',
};

export default withRouter(OperationLog);
